package br.com.trumah.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.trumah.dao.interfaces.RotaDAO;
import br.com.trumah.model.Rota;
import br.com.trumah.model.Usuario;
import br.com.trumah.utils.HibernateUtil;

public class RotaDAOImpl implements RotaDAO{

	
	private Session session = null;
	private Transaction t = null;
	
	@Override
	public void salvar(Rota rota) {
		
		try {

			session = HibernateUtil.getSessionFactory().openSession();
			t = session.beginTransaction();
			session.save(rota);
			t.commit();
			
		} catch (HibernateException ex) {
			
			t.rollback();
			ex.printStackTrace();
			
		} finally {
			session.close();
		}
	}

	@Override
	public Rota obterRota(long id) {
		
		Rota rota = null;
		
		try {
			
			session = HibernateUtil.getSessionFactory().openSession();
			rota = (Rota) session.load(Rota.class, id);
			
			
		} catch (HibernateException ex) {
			
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}
		
		return rota;
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Rota> listar() {
		
		List<Rota> lista = null;
		
		try {
			
			session = HibernateUtil.getSessionFactory().openSession();
			t = session.beginTransaction();
			lista = session.createQuery("from Rota").list();
			t.commit();
			
			
		} catch (HibernateException ex) {
			
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}

		return lista;
		
	}

	@Override
	public void remover(Rota rota) {
		
		try {

			session = HibernateUtil.getSessionFactory().openSession();
			t = session.beginTransaction();
			session.delete(rota);
			t.commit();
			
		} catch (HibernateException ex) {
			
			t.rollback();
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}
	}

	@Override
	public void atualizar(Rota rota) {
		
		try {

			session = HibernateUtil.getSessionFactory().openSession();
			t = session.beginTransaction();
			session.update(rota);
			t.commit();
			
		} catch (HibernateException ex) {
			
			t.rollback();
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}
		

	}

}
